package com.example.kafkademo.commitfailExp;

import org.apache.kafka.clients.consumer.CommitFailedException;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.ProducerConfig;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

/**
 * @author yanyun zhu
 * @version 1.0
 * @date 2021/12/29 8:47
 * 手动阻塞提交  ：
 *
 * org.apache.kafka.clients.consumer.CommitFailedException: Offset commit cannot be completed since the consumer is not part of an active
 * group for auto partition assignment; it is likely that the consumer was kicked out of the group.
 *
 */
public class CommitFailExp {

    public static void main(String[] args) throws InterruptedException {
        Properties props = new Properties();
        props.put("bootstrap.servers", "10.42.25.12:9092,10.42.25.13:9092,10.42.25.15:9092");
        props.put("group.id", "12334");
        props.put("enable.auto.commit", "false");    //默认true, 自动提交
//        props.put("auto.commit.interval.ms", "2000");     //表明 Kafka 每 5 秒会为你自动提交一次位移(默认)
        props.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 5000); // 默认5分钟
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        consumer.subscribe(Arrays.asList("test-a"));
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));
//            process(records); // 处理消息
            try {
                Thread.sleep(6000L);    //模拟异常
                consumer.commitSync();    // 支持自动错误重试
            } catch (CommitFailedException e) {
                e.printStackTrace();
//                handle(e); // 处理提交失败异常
            }
        }
    }


}
